(function ($) {
    var page = "article";
    layui.use(['element', 'form', 'layer', 'laytpl'], function () {
        var model = $(".article-content");
        var layer = layui.layer;
        var form = layui.form;
        var laytpl = layui.laytpl;

        //是否有任务在执行
        var processing = false;
        //富文本编辑器
        var umEditor;

        var channels = [
            {code:"5", description: "前沿"},
            {code:"3", description: "对话"},
            {code:"4", description: "走势"},
            {code:"2", description: "头条"}
        ];

        var authors = loadAuthors();

        //创建对话框
        model.on("click", ".create-item", function (e) {
            laytpl($("#articleForm").html()).render({
                model: "addArticleForm",
                channels: channels,
                authors: authors,
                data: {}
            }, function (content) {
                layer.open({
                    type: 1,
                    title: "创建文章",
                    content: content,
                    offset: 'auto',
                    area: '80%',
                    maxHeight: app.clientHeight() - 50,
                    success: function () {
                        form.render();
                        if (umEditor) {
                            umEditor.destroy();
                            umEditor = UM.getEditor('content');
                        } else {
                            umEditor = UM.getEditor('content');
                        }
                        umEditor.addListener("afterfullscreenchange",function(e){
                            var flag = umEditor._edui_fullscreen_status;
                            if(!flag){
                                umEditor.setHeight(200);
                            }
                        });
                        $("[name='tag']").tagsinput({
                            tagClass: 'big',
                            confirmKeys: [44, 65292, 9, 32]
                        });
                    }
                });
            });
        });

        //新增
        form.on('submit(addArticleForm)', function (data) {
            if (processing || !data.form) {
                return false
            }
            if (data.field.content.length > 409600) {
                layer.msg("内容过长（最长409600个字符）", {icon: 2});
                return false;
            }

            processing = true;

            console.log(data.field);
            debugger;
            $.getJsonData("/hycj/news", data.field, {type: "Post"}).done(function (data) {
                if (data.code != "200") {
                    layer.msg('保存失败', {icon: 2});
                } else {
                    layer.closeAll();
                    layer.msg('操作成功', {icon: 6});
                }

                processing = false;
            }).fail(function () {
                processing = false;
            });
            return false;
        });

        form.verify({
            expireTime: function (value, item) {
                var expireTimeIntVal;
                try {
                    expireTimeIntVal = parseInt(value)
                } catch (error) {
                    return "过期时间只能为数字";
                }
                if (expireTimeIntVal < 6 || expireTimeIntVal >= 24) {
                    return "过期时间只能为6（包括）到24（不包括）小时";
                }
            },
            positiveInteger: function (value, item) {//正整数
                if (value) {
                    try {
                        if (parseInt(value) != value || value < 0) {
                            return "请输入正整数";
                        }
                    } catch (error) {
                        return "请输入正整数";
                    }
                }
            }
        });

        function loadAuthors() {
            var data = [];
            $.getJsonData("/hycj/users/getMediaUser?pageNum=1&pageSize=1000", {}, {type:"Get", async:false}).done(function (result) {
                data = result.datas.items;
            })
            return data;
        }

        //跳转头条管理页面
        $(".article-content").on("click", ".headline", function (e) {
            app.showPage("/admin/headline.html", "头条管理", true);
        });

        //跳转前沿管理页面
        $(".article-content").on("click", ".leading", function (e) {
            app.showPage("/admin/leading.html", "前沿管理", true);
        });

        //跳转走势管理页面
        $(".article-content").on("click", ".trend", function (e) {
            app.showPage("/admin/trend.html", "走势管理", true);
        });

        //跳转对话管理页面
        $(".article-content").on("click", ".dialogue", function (e) {
            app.showPage("/admin/dialogue.html", "对话管理", true);
        });

        app.bindPageEvents(page, function () {
            //上传封面
            $(document).on("click", ".article-form .add-image", function (e) {
                var $addBtn = $(e.currentTarget);
                moon.uploader({
                    //上传成功的回调，回调数据为文件上传的路径。格式如下：[{path:xxx},{path:xxx}]
                    callback: function (uploadRet) {
                        var uploadItem = uploadRet[0];
                        $addBtn.closest(".image-item-container").html("<img src=\"" + uploadItem.path + "\" class=\"image-item add-image\"/>");
                        $("[name='image']").val(uploadItem.path);
                    }
                });
            });

            /**
             * 重置表单
             */
            $(document).on("click", ".article-form :reset", function (e) {
                umEditor.setContent("");
                $(".article-image").html("<i class=\"layui-icon image-placeholder add-image\">&#xe60d;</i>");
                $("[name='tag']").tagsinput('removeAll');
            });
        });
    });
})(jQuery);